import { useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import axios from 'axios'

function PayResult() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()

  const orderNo = useMemo(() => searchParams.get('orderNo') || searchParams.get('out_trade_no') || '', [searchParams])
  const [statusText, setStatusText] = useState<string>('正在确认支付结果...')
  const [error, setError] = useState<string>('')
  const pollingTimer = useRef<number | null>(null)
  const hasNavigatedRef = useRef(false)

  const fetchStatus = async () => {
    if (!orderNo) {
      setError('订单号不存在')
      setStatusText('无法查询支付结果')
      return
    }
    try {
      const endpoints = [
        'http://blogapi.shbwyz.com/order/getPayStatus',
        'http://172.27.2.110/order/getPayStatus'
      ]

      let lastErr: any = null
      for (const url of endpoints) {
        try {
          const response = await axios.post(url, { out_trade_no: orderNo }, {
            timeout: 10000,
            headers: { 'Content-Type': 'application/json' }
          })
          const data = response.data as any
          // 调试日志
          try { console.log('正在获取支付状态..'); console.log('订单号:', orderNo); console.log('支付状态响应:', data) } catch {}
          const code = typeof data?.code === 'number' ? String(data.code) : data?.code
          const tradeStatus = (data?.tradeStatus || data?.trade_status || '').toString()

          if ((code === '10000' || code === '200') && tradeStatus) {
            if (tradeStatus === 'TRADE_SUCCESS') {
              setStatusText('支付成功，正在跳转...')
              if (!hasNavigatedRef.current) {
                hasNavigatedRef.current = true
                navigate(`/payment-success?orderNo=${encodeURIComponent(orderNo)}`, { replace: true })
              }
              return
            }
            if (tradeStatus === 'WAIT_BUYER_PAY') { setStatusText('等待买家付款...'); return }
            if (tradeStatus === 'TRADE_FINISHED') { setStatusText('交易已结束'); return }
            if (tradeStatus === 'TRADE_CLOSED') { setStatusText('交易已关闭'); setError('交易关闭或超时未支付'); return }
            setStatusText(`状态：${tradeStatus}`)
            return
          }

          const ds = (response.data as any)?.data
          const code2 = typeof ds?.code === 'number' ? String(ds.code) : ds?.code
          const ts2 = (
            ds?.tradeStatus || ds?.trade_status ||
            ds?.result?.tradeStatus || ds?.result?.trade_status ||
            ''
          ).toString()
          if (code2 === '10000' && ts2) {
            if (ts2 === 'TRADE_SUCCESS') {
              setStatusText('支付成功，正在跳转...')
              if (!hasNavigatedRef.current) {
                hasNavigatedRef.current = true
                navigate(`/payment-success?orderNo=${encodeURIComponent(orderNo)}`, { replace: true })
              }
              return
            }
            setStatusText(`状态：${ts2}`)
            return
          }
          lastErr = data?.msg || ds?.msg || '未知错误'
        } catch (inner) {
          lastErr = inner
          continue
        }
      }
      if (lastErr) {
        setError(`获取支付状态失败: ${typeof lastErr === 'string' ? lastErr : '网络或跨域错误'}`)
      }
    } catch (e) {
      setError('获取支付状态失败，请稍后重试')
    }
  }

  useEffect(() => {
    // 立即查询一次
    fetchStatus()
    // 开始轮询：每2.5秒一次，最长60秒
    const start = Date.now()
    pollingTimer.current = window.setInterval(async () => {
      if (Date.now() - start > 60000) {
        if (pollingTimer.current) window.clearInterval(pollingTimer.current)
        setError('查询超时，请稍后在订单中心查看或点击重试')
        return
      }
      await fetchStatus()
    }, 2500)

    return () => {
      if (pollingTimer.current) window.clearInterval(pollingTimer.current)
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [orderNo])

  return (
    <div style={{ padding: 24 }}>
      <div style={{ fontSize: 18, marginBottom: 12 }}>支付结果确认</div>
      <div style={{ marginBottom: 8 }}>{statusText}</div>
      {orderNo && <div style={{ color: '#999', fontSize: 12 }}>订单号: {orderNo}</div>}
      {error && (
        <div style={{ marginTop: 16 }}>
          <div style={{ color: '#f53d3d', marginBottom: 12 }}>{error}</div>
          <button onClick={() => { setError(''); setStatusText('正在确认支付结果...'); fetchStatus() }}>重试</button>
        </div>
      )}
    </div>
  )
}

export default PayResult


